from django.db import transaction
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from django.db.models import Q

from stock.models import StockIn
from .models import Supplier
from .serializers import SupplierSerializer
from warehouse_system.pagination import StandardResultsSetPagination


class SupplierViewSet(viewsets.ModelViewSet):
    queryset = Supplier.objects.all()
    serializer_class = SupplierSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination

    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy', 'status']:
            return [IsAuthenticated()]
        return [IsAuthenticated()]

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name')
        if name:
            queryset = queryset.filter(
                Q(name__icontains=name) |
                Q(contact__icontains=name) |
                Q(phone__icontains=name)
            )
        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        # 获取新创建的供应商对象
        supplier = serializer.instance

        # 使用 SupplierSerializer 序列化供应商对象
        supplier_data = SupplierSerializer(supplier).data

        # 构建自定义响应格式
        response_data = {
            "code": 1,
            "data": {
                "id": supplier_data['id'],
                "name": supplier_data['name'],
                "contact": supplier_data['contact'],
                "phone": supplier_data['phone'],
                "address": supplier_data['address'],
                "status": supplier_data['status'],
                "create_time": supplier_data['create_time'],
                "update_time": supplier_data['update_time']
            }
        }

        headers = self.get_success_headers(serializer.data)
        return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        # 使用 SupplierSerializer 序列化更新后的供应商对象
        supplier_data = SupplierSerializer(instance).data

        # 构建自定义响应格式
        response_data = {
            "code": 1,
            "data": {
                "id": supplier_data['id'],
                "name": supplier_data['name'],
                "contact": supplier_data['contact'],
                "phone": supplier_data['phone'],
                "address": supplier_data['address'],
                "status": supplier_data['status'],
                "create_time": supplier_data['create_time'],
                "update_time": supplier_data['update_time']
            }
        }

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(response_data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        try:
            with transaction.atomic():
                # 更新或删除所有相关的 StockIn 记录
                # 例如，将 supplier 字段设置为 None（如果允许 NULL）
                StockIn.objects.filter(supplier=instance).update(supplier=None)

                # 或者，删除所有相关的 StockIn 记录
                # StockIn.objects.filter(supplier=instance).delete()

                # 再删除供应商
                self.perform_destroy(instance)

            # 构建自定义响应格式
            response_data = {
                "code": 1,
                "data": None
            }

            return Response(response_data, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                "code": 0,
                "msg": f"删除失败：{str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def status(self, request, pk=None):
        status = request.data.get('status')
        if status not in [0, 1]:
            return Response({'code': 0, 'msg': '状态值无效'}, status=status.HTTP_400_BAD_REQUEST)

        supplier = self.get_object()
        supplier.status = status
        supplier.save()
        return Response({'code': 1, 'data': None})